package com.homeinns.lyx.trainserver.controller;

import com.homeinns.common.DecreaseStockInput;
import com.homeinns.common.ProductInfoOutput;
import com.homeinns.lyx.trainserver.dataobject.ProductCategory;
import com.homeinns.lyx.trainserver.dataobject.ProductInfo;
import com.homeinns.lyx.trainserver.enums.ProductStatusEnum;
import com.homeinns.lyx.trainserver.repository.ProductCategoryRepository;
import com.homeinns.lyx.trainserver.service.CategoryService;
import com.homeinns.lyx.trainserver.service.ProductService;
import com.homeinns.lyx.trainserver.utils.ResultVOUtil;
import com.homeinns.lyx.trainserver.vo.ProductInfoVO;
import com.homeinns.lyx.trainserver.vo.ProductVO;
import com.homeinns.lyx.trainserver.vo.ResultVO;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/product")
public class ProductRestController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping(value = "/list",name = "查找所有商品")
    public ResultVO<ProductVO> findAllProduct(){

        List<ProductInfo> productInfoList=productService.findAllProduct(ProductStatusEnum.UP.getCode());

        List<Integer> ids=productInfoList.stream().map(x -> x.getCategoryType()).collect(Collectors.toList());

        List<ProductCategory> categoryList=categoryService.findByCategoryTypeIn(ids);

        List<ProductVO> productVOS = new ArrayList<>();

        for(ProductCategory productCategory:categoryList){
            ProductVO productVO=new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productCategory.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();

            for(ProductInfo productInfo:productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO=new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOS(productInfoVOList);
            productVOS.add(productVO);
        }
        return ResultVOUtil.success(productVOS);
    }

    @PostMapping(value = "/listForOrder",name = "根据商品id查询商品信息")
    public List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIds){

        return productService.findList(productIds);
    }

    @PostMapping(value = "/decreaseStock",name = "减少库存")
    public void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputs){
        productService.decreaseStock(decreaseStockInputs);
    }
}
